package com.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.store.dto.ProductCreateRequest;
import com.store.dto.ProductQueryRequest;
import com.store.dto.ProductUpdateRequest;
import com.store.entity.Category;
import com.store.entity.Product;
import com.store.mapper.CategoryMapper;
import com.store.mapper.ProductMapper;
import com.store.vo.ProductVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品服务
 * 
 * @author Store Team
 */
@Service
@RequiredArgsConstructor
public class ProductService {

    private final ProductMapper productMapper;
    private final CategoryMapper categoryMapper;

    /**
     * 分页查询商品列表
     */
    public IPage<ProductVO> getProductList(ProductQueryRequest request) {
        // 构建查询条件
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        
        // 商品名称模糊查询
        if (StringUtils.hasText(request.getName())) {
            wrapper.like(Product::getName, request.getName());
        }
        
        // 分类ID
        if (request.getCategoryId() != null) {
            wrapper.eq(Product::getCategoryId, request.getCategoryId());
        }
        
        // 条形码
        if (StringUtils.hasText(request.getBarcode())) {
            wrapper.eq(Product::getBarcode, request.getBarcode());
        }
        
        // 状态
        if (request.getStatus() != null) {
            wrapper.eq(Product::getStatus, request.getStatus());
        }
        
        // 是否热销
        if (request.getIsHot() != null) {
            wrapper.eq(Product::getIsHot, request.getIsHot());
        }
        
        // 价格区间
        if (request.getMinPrice() != null) {
            wrapper.ge(Product::getPrice, request.getMinPrice());
        }
        if (request.getMaxPrice() != null) {
            wrapper.le(Product::getPrice, request.getMaxPrice());
        }
        
        // 库存预警
        if (request.getStockAlert() != null && request.getStockAlert()) {
            wrapper.apply("stock <= min_stock");
        }
        
        // 排序
        if (StringUtils.hasText(request.getSortField())) {
            boolean isAsc = "asc".equalsIgnoreCase(request.getSortOrder());
            switch (request.getSortField()) {
                case "price":
                    wrapper.orderBy(true, isAsc, Product::getPrice);
                    break;
                case "sales":
                    wrapper.orderBy(true, isAsc, Product::getSales);
                    break;
                case "createTime":
                    wrapper.orderBy(true, isAsc, Product::getCreateTime);
                    break;
                default:
                    wrapper.orderByDesc(Product::getCreateTime);
            }
        } else {
            // 默认按创建时间降序
            wrapper.orderByDesc(Product::getCreateTime);
        }
        
        // 分页查询
        Page<Product> page = new Page<>(request.getPage(), request.getPageSize());
        IPage<Product> productPage = productMapper.selectPage(page, wrapper);
        
        // 转换为VO
        IPage<ProductVO> voPage = productPage.convert(this::convertToVO);
        
        return voPage;
    }

    /**
     * 根据ID获取商品详情
     */
    public ProductVO getProductById(Long id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        return convertToVO(product);
    }

    /**
     * 创建商品
     */
    @Transactional(rollbackFor = Exception.class)
    public ProductVO createProduct(ProductCreateRequest request) {
        // 验证分类是否存在
        Category category = categoryMapper.selectById(request.getCategoryId());
        if (category == null) {
            throw new RuntimeException("商品分类不存在");
        }
        
        // 验证条形码是否重复
        if (StringUtils.hasText(request.getBarcode())) {
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Product::getBarcode, request.getBarcode());
            Long count = productMapper.selectCount(wrapper);
            if (count > 0) {
                throw new RuntimeException("条形码已存在");
            }
        }
        
        // 创建商品
        Product product = new Product();
        BeanUtils.copyProperties(request, product);
        product.setSales(0); // 初始销量为0
        
        // 设置默认值
        if (product.getMinStock() == null) {
            product.setMinStock(10); // 默认最低库存为10
        }
        if (product.getStatus() == null) {
            product.setStatus(1); // 默认上架
        }
        if (product.getIsHot() == null) {
            product.setIsHot(0); // 默认不是热销
        }
        
        productMapper.insert(product);
        
        return convertToVO(product);
    }

    /**
     * 更新商品
     */
    @Transactional(rollbackFor = Exception.class)
    public ProductVO updateProduct(ProductUpdateRequest request) {
        // 验证商品是否存在
        Product product = productMapper.selectById(request.getId());
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        
        // 验证分类是否存在
        if (request.getCategoryId() != null) {
            Category category = categoryMapper.selectById(request.getCategoryId());
            if (category == null) {
                throw new RuntimeException("商品分类不存在");
            }
        }
        
        // 验证条形码是否重复
        if (StringUtils.hasText(request.getBarcode()) && !request.getBarcode().equals(product.getBarcode())) {
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Product::getBarcode, request.getBarcode());
            wrapper.ne(Product::getId, request.getId());
            Long count = productMapper.selectCount(wrapper);
            if (count > 0) {
                throw new RuntimeException("条形码已存在");
            }
        }
        
        // 更新商品（忽略null值，避免覆盖原有数据）
        if (request.getName() != null) product.setName(request.getName());
        if (request.getCategoryId() != null) product.setCategoryId(request.getCategoryId());
        if (request.getBarcode() != null) product.setBarcode(request.getBarcode());
        if (request.getPrice() != null) product.setPrice(request.getPrice());
        if (request.getCostPrice() != null) product.setCostPrice(request.getCostPrice());
        if (request.getStock() != null) product.setStock(request.getStock());
        if (request.getMinStock() != null) product.setMinStock(request.getMinStock());
        if (request.getImage() != null) product.setImage(request.getImage());
        if (request.getDescription() != null) product.setDescription(request.getDescription());
        if (request.getStatus() != null) product.setStatus(request.getStatus());
        if (request.getIsHot() != null) product.setIsHot(request.getIsHot());
        
        productMapper.updateById(product);
        
        return convertToVO(product);
    }

    /**
     * 删除商品
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteProduct(Long id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        
        // 检查商品状态，上架的商品不允许删除
        if (product.getStatus() == 1) {
            throw new RuntimeException("请先下架商品再删除");
        }
        
        // 检查商品是否有销量，有销量的商品不允许删除
        if (product.getSales() != null && product.getSales() > 0) {
            throw new RuntimeException("该商品已有销售记录，不允许删除");
        }
        
        productMapper.deleteById(id);
    }

    /**
     * 批量删除商品
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteProducts(List<Long> ids) {
        for (Long id : ids) {
            deleteProduct(id);
        }
    }

    /**
     * 获取热销商品
     */
    public List<ProductVO> getHotProducts(Integer limit) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getStatus, 1); // 只查询上架的商品
        wrapper.eq(Product::getIsHot, 1); // 热销商品
        wrapper.orderByDesc(Product::getSales); // 按销量降序
        wrapper.last("LIMIT " + (limit != null ? limit : 10));
        
        List<Product> products = productMapper.selectList(wrapper);
        return products.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取库存预警商品
     */
    public List<ProductVO> getStockAlertProducts() {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.apply("stock <= min_stock");
        wrapper.eq(Product::getStatus, 1); // 只查询上架的商品
        wrapper.orderByAsc(Product::getStock);
        
        List<Product> products = productMapper.selectList(wrapper);
        return products.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 转换为VO对象
     */
    private ProductVO convertToVO(Product product) {
        ProductVO vo = new ProductVO();
        BeanUtils.copyProperties(product, vo);
        
        // 查询分类名称
        Category category = categoryMapper.selectById(product.getCategoryId());
        if (category != null) {
            vo.setCategoryName(category.getName());
        }
        
        // 判断是否库存预警（添加空指针检查）
        Integer stock = product.getStock();
        Integer minStock = product.getMinStock();
        if (stock != null && minStock != null) {
            vo.setStockAlert(stock <= minStock);
        } else {
            vo.setStockAlert(false);
        }
        
        return vo;
    }

}

